import React,{useEffect,useState} from 'react'
import {useParams,useNavigate} from "react-router-dom"
import axios from 'axios'
import { Image } from 'react-vant';
import { ActionBar } from 'react-vant';
import { CartO, ChatO, ShopO } from '@react-vant/icons'
import {useDispatch} from "react-redux"
import * as action from "../action"

function Detail() {
   let navigate = useNavigate()
   let dispatch = useDispatch()
  let [detailobj, setDetailobj] = useState({})
  let {id} = useParams()
  // 在详情页有接口，前端给后端传id，后端返回前端数据，前端渲染数据
  useEffect(()=>{
    axios.get("/api/list").then(res=>{
         let obj = res.data.filter((item)=>item.id === id)[0]
         setDetailobj(obj)
    })
  

  },[])
  let addShop = (item)=>{
     console.log(item);
     // 三步走第一步，dispatch触发action里的方法
     dispatch(action.addshop(item))
  }
  return (
      //  Object.keys 将一个对象的key转换为数组
      Object.keys(detailobj).length && <div>
           <Image width='100vw' height='auto' src={detailobj.img} />
           <h3>商品名称：{detailobj.tit}</h3>
           <h3>描述:{detailobj.des}  <span>价格:{detailobj.price}</span></h3>
           <div className='demo-action-bar'>
      <ActionBar>
        <ActionBar.Icon
          icon={<ChatO />}
          text='客服'
          onClick={() => console.log('chat click')}
        />
        <ActionBar.Icon
          icon={<CartO />}
          text='购物车'
          onClick={() => navigate("/home/shopcar")}
        />
        <ActionBar.Icon
          icon={<ShopO />}
          text='店铺'
          onClick={() => console.log('shop click')}
        />
        <ActionBar.Button
          type='danger'
          text='加入购物车'
          onClick={() => addShop(detailobj)}
        />
      </ActionBar>
    </div>
      </div>
  )
}

export default Detail